package hdf5_helper

import (
	"fmt"
	"gonum.org/v1/hdf5"
	"github.com/sbinet/npyio"
	"os"
	"log"
)

func Readh5(path string) ([][]uint8,[][]uint8,[][]uint8) {
	ff, err := hdf5.OpenFile(path, hdf5.F_ACC_RDONLY)
	if err != nil {
			panic(err)
	}
	defer ff.Close()
	grp,err := ff.OpenDataset("/fixed_keys/metadata")

	data := [60000][60]uint8{}
	if err != nil { panic(fmt.Errorf("failed to open dataset: %s", err))}
	grp.Read(&data)
	defer grp.Close()

	keys := [][]uint8{}
	nonce0s := [][]uint8{}
	nonce1s := [][]uint8{}
	for i:=0;i<60000;i++{
		i:=i
		keys = append(keys,data[i][0:8])
		nonce0s = append(nonce0s,data[i][16:24])
		nonce1s = append(nonce1s,data[i][24:32])
	}
	return keys,nonce0s,nonce1s
}

func Readpredict_r(path string) ([]float32){
	f, err := os.Open(path)
	if err != nil {log.Fatal(err)}
	defer f.Close()
	var m []float32
	err = npyio.Read(f, &m)
	if err != nil {log.Fatal(err)}
	return m
}

func Readpredict_c(path string, class int) ([][]float32){
	f, err := os.Open(path)
	if err != nil {log.Fatal(err)}
	defer f.Close()
	var m []float32
	var re [][]float32
	err = npyio.Read(f, &m)
	if err != nil {log.Fatal(err)}
	for i:=0;i<(len(m)/class);i++{
		re = append(re,m[i*class:i*class+class])
	}
	return re
}

func Show_h5(prefix string, obj *hdf5.CommonFG) {
	//显示当前节点的 名称,类型
	fmt.Printf("%s(%s) %s \n", prefix, obj.Type(), obj.Name())
	//获取当前节点中包含的,下级节点数目
	ObjNum, _ := obj.NumObjects()
	if ObjNum < 1 {
			return
	}
	prefix = prefix[:len(prefix)-1] + " |-" //前缀,缩进一层
	for ii := uint(0); ii < ObjNum; ii++ {
			ObjName, _ := obj.ObjectNameByIndex(ii) //节点name
			ObjType, _ := obj.ObjectTypeByIndex(ii) //节点type
			if ObjType == hdf5.H5G_GROUP { //是GROUP
			   //fmt.Printf("%s(%s) %s \n", prefix, ObjType, ObjName)
					obj, _ := obj.OpenGroup(ObjName)
					Show_h5(prefix, &obj.CommonFG) //递归调用
					obj.Close()
			} else if ObjType == hdf5.H5G_DATASET { //是DATASET
			   fmt.Printf("%s(%s) %s \n", prefix, ObjType, ObjName)
			}
	}

}

func Readmeta(path string, bytes int) ([][]uint8){
	f, err := os.Open(path)
	if err != nil {log.Fatal(err)}
	defer f.Close()
	var m []uint8
	var re [][]uint8
	err = npyio.Read(f, &m)
	if err != nil {log.Fatal(err)}
	for i:=0;i<(len(m)/bytes);i++{
		re = append(re,m[i*bytes:i*bytes+bytes])
	}
	return re
}

